//
//  AIGirlDiscoverCollectionReusableView.swift
//  AIGirl
//
//  Created by Rae on 2023/12/28.
//

import UIKit

class AIGirlDiscoverPicCollectionReusableView: UICollectionReusableView {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Discover_topBg").end()
    var bannerPushClosure: ((_ url: String) -> Void)?
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            iconImageView
        }
        iconImageView.leading(10).trailing(10).top(0).bottom(0)
        iconImageView.isUserInteractionEnabled = true
        let tapG = UITapGestureRecognizer(target: self, action: #selector(clickBannerView))
        iconImageView.addGestureRecognizer(tapG)
        
        if GlobalTool.bannerModel.count > 0 {
            let md = GlobalTool.bannerModel.first
            iconImageView.loadImage(url: md?.imageUrl)
        }
    }
    
    @objc private func clickBannerView(){
        
        if GlobalTool.bannerModel.count > 0 {
            let md = GlobalTool.bannerModel.first
            //0内部webview 1外部网页 2内部跳转
            
            if md?.type == 0 {
                guard let targetUrl = md?.targetUrl else {
                    "Invalid link".toast_error
                    return
                }
                bannerPushClosure?(targetUrl)
            }else if md?.type == 1{
                guard let targetUrl = md?.targetUrl else {
                    "Invalid link".toast_error
                    return
                }
                if let url = URL(string: targetUrl) {
                    // 检查是否可以打开链接
                    if UIApplication.shared.canOpenURL(url) {
                        // 打开链接
                        UIApplication.shared.open(url, options: [:], completionHandler: nil)
                    } else {
                        "Unable to open link".toast_error
                    }
                } else {
                    "Invalid link".toast_error
                }
            }else if md?.type == 2{
                bannerPushClosure?("")
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class AIGirlDiscoverCollectionReusableView: UICollectionReusableView {
        
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private var dataArray: [AIGirlDiscoverCateModel] = [
        AIGirlDiscoverCateModel(title: "🔥Hot",imgStr: "",select: true),
        AIGirlDiscoverCateModel(title: "New",imgStr: "",select: false),
        AIGirlDiscoverCateModel(title: "VIP",imgStr: "AIGirl_Discover_pre",selImgStr: "AIGirl_Discover_preLight",select: false)
    ]
    var cateArray: [String] = [] {
        didSet{
//            if cateArray.count > 3 {
//                let index =  cateArray.count
//                for index in 0..<index {
//                    let title = cateArray[index + 3]
//                    let model = AIGirlDiscoverCateModel(title: title,imgStr: "",select: false)
////                    if dataArray.count != cateArray.count {
//                        dataArray.append(model)
////                    }
//                    
//                }
             
            if dataArray.count == 3 {
                for title in cateArray {
                    let model = AIGirlDiscoverCateModel(title: title,imgStr: "",select: false)
                    dataArray.append(model)
                }
            }
                collectionView.reloadData()
//            }
        }
    }
    var updateDataClosure: ((_ label: String) -> Void)?
    var updateTypeClosure: ((_ type: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = "#262C61".toColor
        
        subviews{
            collectionView
        }
        
        collectionView.leading(0).trailing(0).height(30).centerVertically()
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        layout.scrollDirection = .horizontal
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlDiscoverCateItem.self, forCellWithReuseIdentifier: AIGirlDiscoverCateItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension AIGirlDiscoverCollectionReusableView: UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlDiscoverCateItem.description(), for: indexPath) as? AIGirlDiscoverCateItem else { return UICollectionViewCell() }
        item.model = dataArray[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [AIGirlDiscoverCateModel]()
        dataArray.forEach { model in
            var itemModel = model
            itemModel.select = false
            models.append(itemModel)
        }
        models[indexPath.row].select = true
        dataArray = models
        collectionView.reloadData()
        if indexPath.row > 2 {
            updateDataClosure?(models[indexPath.row].title)
        }else{
            updateTypeClosure?(indexPath.row + 1)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = dataArray[indexPath.row]
        var w = model.title.caculateWidth(CGSize(width: 50, height: 30), 14.font_regular!)
        w = w + 30.0
        return CGSize(width: w, height: 30)
    }
}
